package com.iflytek.cosmo.ocr.common.schedule;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.iflytek.cosmo.ocr.common.core.BeanHelper;
import com.iflytek.cosmo.ocr.model.entity.ExportTaskEntity;
import com.iflytek.cosmo.ocr.service.ExportTaskService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 文件导出任务清理 job
 *
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019/12/3 15:25
 */
@Component
public class ExportTaskCleanJob {
    private static final Logger logger = LoggerFactory.getLogger(ExportTaskCleanJob.class);

    @Value("${file.export.expire.day:3}")
    private int keepAliveDays;

    @Autowired
    private ExportTaskService exportTaskService;

    // 每天 3:00 执行
    @Scheduled(cron = "${file.export.clean.cron}")
    public void reportCurrentTimeCron() throws InterruptedException {
        logger.info("开始清理文件导出任务");
        ExportTaskService exportService = BeanHelper.getExportServiceBean();
        List<ExportTaskEntity> expiredTasks = exportService.findExpiredTask(keepAliveDays, TimeUnit.DAYS);
        if (CollectionUtils.isEmpty(expiredTasks)) {
            logger.info("暂无过期导出任务数据");
            return;
        }
        logger.info("查询到待清理的导出任务数据{}条", CollectionUtils.size(expiredTasks));

        try {
            exportService.cleanup(expiredTasks);
        }
        catch (Exception e) {
            logger.warn("清理文件导出任务异常", e);
        }

        logger.info("清理文件导出任务结束");
    }

}
